
<template>
  <div class="resource-main-box service-information-main new-page">
    <a-form-model layout="inline" :model="search" class="comm-search" :style="`width: calc(100% - ${sideMenuWidth} - 33px)`">
      <!-- 筛选条件与查询 -->
      <!-- 航空公司 -->
      <a-form-model-item label="">
        <a-select
          v-model="search.airline"
          show-arrow
          mode="multiple"
          :max-tag-count="1"
          style="minWidth: 100%"
          placeholder="航空公司"
          allow-clear
          @change="changeAirline"
        >
          <a-icon slot="suffixIcon" :component="require('@/assets/icon/arrow-down-bold.svg')" />
          <a-select-option v-for="selectItem in ftmAirlineList" :key="selectItem.id" :value="selectItem.name">
            {{ selectItem.name }}
          </a-select-option>
        </a-select>
      </a-form-model-item>
      <!-- 机型 -->
      <a-form-model-item label="">
        <airModel v-model="search.model" mode="multiple" :data-source="servftmPlaneModelList" @change="changeModelline" />
      </a-form-model-item>
      <!-- 机队 -->
      <a-form-model-item label="">
        <a-select
          v-model="search.fleet"
          show-arrow
          style="minWidth: 100%"
          placeholder="机队"
          mode="multiple"
          :max-tag-count="1"
          allow-clear
          @change="changeFleet"
        >
          <a-icon slot="suffixIcon" :component="require('@/assets/icon/arrow-down-bold.svg')" />
          <a-select-option v-for="selectItem in servftmFleetListFilter" :key="selectItem.id" :value="selectItem.name">
            {{ selectItem.name }}
          </a-select-option>
        </a-select>
      </a-form-model-item>
      <a-form-model-item label="">
        <tailNumber v-model="search.tailnumber" value-key="tailnumber" name-key="tailnumber" :data-source="servftmAirplaneListFilter" />
      </a-form-model-item>
      <a-form-model-item label="">
        <a-select
          :key="Math.random()"
          v-model="search.summaryItem"
          style="minWidth: 100%"
          placeholder="汇总项"
        >
          <a-icon slot="suffixIcon" :component="require('@/assets/icon/arrow-down-bold.svg')" />
          <a-select-option v-for="selectItem in SummaryItemsList" :key="selectItem.id" :value="selectItem.summary">
            <a-tooltip placement="left" :destroy-tooltip-on-hide="true" :mouse-enter-delay="0.2">
              <template slot="title">
                <span>{{ selectItem.summary }}</span>
              </template>
              {{ selectItem.summary }}
            </a-tooltip>

          </a-select-option>
        </a-select>
      </a-form-model-item>
      <a-form-model-item label="">
        <a-select
          value="raw quantity"
          style="minWidth: 100%"
          show-arrow
          placeholder="图表类型"
        >
          <a-icon slot="suffixIcon" :component="require('@/assets/icon/arrow-down-bold.svg')" />
          <a-select-option value="raw quantity">
            raw quantity
          </a-select-option>
        </a-select>
      </a-form-model-item>

      <a-form-model-item class="service-information-btn-box">
        <a-button type="primary" :loading="servServiceInfoLoading" @click="searchData">
          查询
        </a-button>
        <a-button type="default" class="ml-8" ghost :loading="servServiceInfoLoading" @click="resetSearchHandler">
          重置
        </a-button>

      </a-form-model-item>
    </a-form-model>
    <a-table
      size="middle"
      class="table-border"
      :columns="columns"
      :data-source="servServiceInfoList"
      :pagination="{
        showTotal:(total)=> `共 ${total} 条数据`,
        showSizeChanger: true,//设置每页显示数据条数
        showQuickJumper: true,
        size:'big',
        current:pagination.pageNum,
        pageSize:pagination.pageSize,
        total:pagination.total
      }"
      :row-key="(row,index) =>row.id"
      :loading="servServiceInfoLoading"
      @change="changeTable"
    >
      <div slot="rawData" slot-scope="row" class="progressBox">
        <span>{{ row.minValue }}</span>
        <div class="progressBar">
          <div class="currentDataBar" :style="{width:row.currentWidth+'%'}" :class="barClassHandler(row)" />
          <!-- <a-tooltip placement="bottom">
            <template slot="title">
              <span>平均值：{{ row.avgValue }}</span>
            </template>
            <div class="dataBar avgData" :style="{left:row.avgWidth+'%'}" />
          </a-tooltip>
          <a-tooltip placement="bottom">
            <template slot="title">
              <span>操作警报限制：{{ row.operationalAlertLimit }}</span>
            </template>
            <div class="dataBar opData" :style="{left:row.opAlertWidth+'%'}" />
          </a-tooltip>
          <a-tooltip placement="bottom">
            <template slot="title">
              <span>服务警报限制：{{ row.serviceAlertLimit }}</span>
            </template>
            <div class="dataBar serData" :style="{left:row.serAlertWidth+'%'}" />
          </a-tooltip> -->

        </div>
        <span>{{ row.maxValue }}</span>
      </div>
      <template slot="checkEchart" slot-scope="text,record">
        <a-button type="link" size="small" @click="checkEchart(record)">
          查看图表
        </a-button>
      </template>
      <div slot="header">
        <span>{{ rawDataName }}</span>
        <!-- <div>fleet avg:{{ record.avgValue }}</div> -->
      </div>

    </a-table>
    <a-modal
      v-model="visible"
      :mask-closable="false"
      title=""
      :width="888"
      :dialog-style="{height:'600px'}"
      :footer="null"
      @ok="handleOk()"
    >
      <span slot="closeIcon" class="c-dialog-close-icon"><a-icon :component="require('@/assets/icon/close.svg')" /></span>

      <div class="c-dialog-title fw-500">图表</div>
      <div>
        <table class="chart-table" border="1px" width="100%" style="table-layout:fixed;border-right: 0;border-bottom: 0;">
          <tr style="text-align:center">
            <td class="ct-th">机号</td>
            <td>{{ tailNumber||'--' }}</td>
            <td class="ct-th">最新数据值</td>
            <td>{{ servServiceEchartData.datas&&servServiceEchartData.datas[0]?servServiceEchartData.datas[0].value:'--' }}</td>
            <td class="ct-th">维修限额</td>
            <td>{{ servServiceEchartData.serviceAlertLimit||'--' }}</td>
          </tr>
          <tr style="text-align:center">
            <td class="ct-th">最新数据的日期</td>
            <td>{{ servServiceEchartData.nowTime?$moment.utc(servServiceEchartData.nowTime).format('YYYY-MM-DD'):'--' }}</td>
            <td class="ct-th">斜率限额</td>
            <td>{{ servServiceEchartData.trendSlopeLimit||'--' }}</td>
            <td class="ct-th">保养限额</td>
            <td>{{ servServiceEchartData.operationalAlertLimit||'--' }}</td>
          </tr>
        </table>
        <div id="echart" ref="echart" style="height:400px;width:100%;margin-top:20px;" />
        <div class="legendBox">
          <div class="APU-item">
            <div />
            <span>{{ servServiceEchartData.summaryName }}</span>
          </div>
          <div class="recent-item">
            <div />
            <span>Most Recent Date Point</span>
          </div>
          <div v-if="servServiceEchartData.serviceAlertLimit<=maxY&&servServiceEchartData.serviceAlertLimit>=minY" class="service-limit-item">
            <img src="../../../assets/icon/limit.png" alt="">
            <span>Service Alert Limit</span>
          </div>
          <div v-if="servServiceEchartData.operationalAlertLimit<=maxY&&servServiceEchartData.operationalAlertLimit>=minY" class="service-limit-item">
            <img src="../../../assets/icon/limit-red.png" alt="">
            <span>Operational Limit</span>
          </div>
        </div>
      </div>
    </a-modal>

  </div>
</template>

<script>
import { mapState, mapActions, mapMutations, mapGetters } from 'vuex';
import rowClass from '@/pages/common/rowClass';
import tailNumber from '@/pages/components/tailNumber';
import airModel from '@/pages/components/airModel';
export default {
  components: {
    tailNumber,
    airModel
  },
  mixins: [rowClass],
  data() {
    return {
      tailNumber: null,
      visible: false,
      maxY: 0,
      minY: 0,
      test: 0,
      search: {
        summaryItem: ''
      },
      rawDataName: null,
      columns: Object.freeze([
        {
          title: '机号',
          dataIndex: 'tailNumber',
          align: 'left',
          sorter: true,
          width: 100
        },
        {
          title: '警报',
          align: 'left',
          dataIndex: 'alert',
          width: 100
        },
        {
          title: '位置',
          align: 'left',
          sorter: true,
          dataIndex: 'location',
          width: 100,
          customRender: (value) => {
            return value || '--';
          }
        },
        {
          title: '当前数据',
          align: 'left',
          dataIndex: 'currentData',
          width: 100
        },
        {
          title: '时间单位',
          align: 'left',
          dataIndex: 'unit',
          width: 100,
          customRender: (value) => {
            return value || '--';
          }
        },
        {
          // title: '原始数据',
          align: 'left',
          dataIndex: 'rawData',
          scopedSlots: { customRender: 'rawData' },
          slots: { title: 'header' }
        },
        {
          title: '触发时间',
          sorter: true,
          align: 'left',
          dataIndex: 'createTime',
          width: 100,
          customRender: (value) => {
            return value ? this.$moment.utc(value).format('YYYY-MM-DD HH:mm') : '--';
          }
        },
        {
          title: '查看图表',
          align: 'left',
          dataIndex: 'echart',
          width: 100,
          scopedSlots: { customRender: 'checkEchart' }
        }
      ])

    };
  },
  computed: {
    ...mapState('serviceInformation', [
      'servServiceInfoList',
      'servServiceEchartData',
      'servServiceInfoLoading',
      'pagination'
    ]),
    ...mapState('fraMonitoring', [
      'servftmFleetListFilter',
      'servftmPlaneModelList',
      'servftmAirplaneListFilter',
      'ftmAirlineList',
      'ftmAirplaneList',
      'SummaryItemsList'
    ]),
    ...mapGetters('setting', ['sideMenuWidth']),
    avgValue() {
      return this.servServiceInfoList?.[0]?.rawData?.avgValue ?? 0;
    }
  },
  async mounted() {
    await this.getSummaryItems();
    this.changeAirline();
    this.search.summaryItem = this.SummaryItemsList?.[0]?.summary ?? '';
    this.changeTable({ current: 1 });
  },
  methods: {
    ...mapActions('serviceInformation', [
      'getServServiceInfoList',
      'getServServiceEchartData'

    ]),
    ...mapActions('fraMonitoring', [
      'getSummaryItems',
      'getFtmAirplaneListFilterserv', // 机号
      'getFtmPlaneModelListFilterServ', // 机型
      'getFtmFleetFilterServ' // 机队
    ]),
    ...mapMutations('serviceInformation', [
      'setState'
    ]),

    searchData() {
      this.setState({ key: 'pagination', payload: { ...this.pagination, pageNum: 1 }});
      this.changeTable({ current: 1 });
    },
    changeTable({ current, pageSize = 10 }, filters, sorter) {
      const params = { ...this.search };
      switch (sorter?.field) {
        case 'unit':
          sorter.order === 'ascend' ? params['isUnitOrder'] = 0 : sorter.order === 'descend' ? params['isUnitOrder'] = 1 : '';
          break;
        case 'tailNumber':
          sorter.order === 'ascend' ? params['isTailNumberOrder'] = 0 : sorter.order === 'descend' ? params['isTailNumberOrder'] = 1 : '';
          break;
        case 'location':
          sorter.order === 'ascend' ? params['isPosOrder'] = 0 : sorter.order === 'descend' ? params['isPosOrder'] = 1 : '';
          break;
        case 'createTime':
          sorter.order === 'ascend' ? params['isTimeOrder'] = 0 : sorter.order === 'descend' ? params['isTimeOrder'] = 1 : '';
          break;
      }

      this.setState({ key: 'pagination', payload: { ...this.pagination, pageNum: current, pageSize }});
      this.getData(params);
    },

    initCharts(data, theLastoneData) {
      const max = [...data, ...theLastoneData].flatMap(item => +item[1]);
      const maxNum = Math.max(...max);
      const dotAfLen = (String(maxNum).split('.')[1] ?? '').length;
      let step = maxNum * 0.05;

      if (dotAfLen !== 0) {
        step = this.$np.round(step, dotAfLen);
      } else {
        step = Math.ceil(step);
      }

      this.maxY = maxNum + step;
      this.minY = Math.min(...max) - step;

      console.log(maxNum, step, this.maxY, dotAfLen);
      const myChart = this.$echarts.init(this.$refs.echart);
      const lastDate = theLastoneData?.[0]?.[0] ?? new Date();

      const lastDateF = this.$moment(lastDate).format('YYYY-MM-DD');
      const firstDateF = this.$moment(lastDateF).add(-6, 'months').add(-1, 'day').format('YYYY-MM-DD');
      const option = {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'cross'
          }
        },
        title: {
          left: 'center',
          text: this.servServiceEchartData.summaryName ?? '',
          subtextStyle: { // 对应样式
            color: '#F27CDE',
            fontSize: 14,
            left: 'left'
          }
        },
        grid: {
          top: 74,
          left: 60,
          right: 44
        },
        xAxis: {
          type: 'time',
          name: '时间',
          // 开始时间
          min: new Date(firstDateF),

          splitLine: {
            show: false
          }
        },
        yAxis: {
          max: this.maxY,
          min: this.minY,
          name: this.servServiceEchartData.valueUnit ?? ''
        },
        series: [{
          symbolSize: 10,
          data,
          markLine: {
            symbol: ['none', 'none'], // 去掉箭头
            itemStyle: {
              normal: {
                label: { show: false, position: 'left' }
              }
            },
            data: [
              {
                name: '维修限额',
                yAxis: this.servServiceEchartData.serviceAlertLimit,
                silent: true,
                lineStyle: { type: 'dashed', color: '#F5A623' }
              },
              {
                name: '保养限额',
                yAxis: this.servServiceEchartData.operationalAlertLimit,
                silent: true,
                lineStyle: { type: 'dashed', color: '#E60000' }
              }
            ]
          },
          type: 'scatter',
          itemStyle: {
            normal: {
              color: '#EE5396'
            }
          },
          name: this.servServiceEchartData.summaryName ?? ''
        },
        {
          symbolSize: 10,
          name: 'Most Recent Date Point',
          data: theLastoneData,
          type: 'scatter',
          itemStyle: {
            normal: {
              color: '#1192E8'
            }
          }
        }]
      };
      // 绘制图表
      myChart.setOption(option);
    },
    // 关闭弹窗
    handleOk() {
      this.visible = false;
    },
    // 航空公司
    changeAirline() {
      const params = {
        airline: this.search.airline || undefined,
        model: this.search.model || undefined,
        fleet: this.search.fleet || undefined
      };
      this.getFtmPlaneModelListFilterServ(params);
      this.getFtmFleetFilterServ(params);
      this.getFtmAirplaneListFilterserv(params);
    },
    // 机型
    changeModelline() {
      const params = {
        airline: this.search.airline || undefined,
        model: this.search.model || undefined,
        fleet: this.search.fleet || undefined
      };
      this.getFtmFleetFilterServ(params);
      this.getFtmAirplaneListFilterserv(params);
    },
    // 机队 影响改变机号
    changeFleet() {
      const params = {
        airline: this.search.airline || undefined,
        model: this.search.model || undefined,
        fleet: this.search.fleet || undefined
      };
      this.getFtmAirplaneListFilterserv(params);
    },
    barClassHandler(row) {
      switch (row.alertDirection ?? '') {
        case 'both':
          if (+row.currentValue === row.serviceAlertLimit) {
            return 'normal-data-bar';
          }
          break;
        case 'upper':
          if (+row.currentValue < row.serviceAlertLimit) {
            return 'normal-data-bar';
          }
          break;
        case 'lower':
          if (+row.currentValue > row.serviceAlertLimit) {
            return 'normal-data-bar';
          }
          break;
      }
    },
    // 重置
    resetSearchHandler() {
      this.search = {
        summaryItem: this.SummaryItemsList?.[0]?.summary ?? ''
      };

      for (const key in this.search) {
        if (Object.hasOwnProperty.call(this.search, key)) {
          const element = this.search[key];
          if (!element || element.length === 0) {
            delete this.search[key];
          }
        }
      }
      this.changeAirline();
      this.changeTable({ current: 1 });
    },
    // 获取table
    async getData(params) {
      await this.getServServiceInfoList(params);
      this.rawDataName = params.summaryItem;
    },
    // 弹出Echart框
    checkEchart(e) {
      this.tailNumber = e.tailNumber;
      this.visible = true;
      this.renderChart(e);
    },
    // 获取echart数据
    async renderChart(e) {
      const data = {
        itemName: e.itemName,
        serviceConfId: e.serviceConfId,
        tailNumber: e.tailNumber
      };
      await this.getServServiceEchartData(data);
      const servServiceEchartData = [...(this.servServiceEchartData?.datas ?? []).filter(item => item.value && +item.value >= 0)];

      const initEchartsData = [];
      const lastoneData = [];
      const lastIndex = servServiceEchartData.findIndex(item => item.value && +item.value >= 0);
      const lastData = servServiceEchartData.splice(lastIndex, 1);
      lastoneData.push([lastData?.[0]?.time, lastData?.[0]?.value]);
      servServiceEchartData.forEach(item => {
        const singerData = [];
        singerData.splice(0, 0, item.time, item.value);
        initEchartsData.push(singerData);
      });
      this.$nextTick(() => {
        this.initCharts(initEchartsData, lastoneData);
      });
    }
  }
};
</script>

<style lang="less">
  .chart-table{
    border: 1px solid #EBECEF;
    tr{
      height: 32px;
    }

    .ct-th{
      background-color: #F5F7FA;
    }
  }
.service-information-main{
  padding:0;
.ant-table-thead {
  height: 48px;
}

.ant-table-tbody > tr > td {
  border-bottom: unset;
  height: 48px;
}
.ant-table-row-cell-break-word{
  padding: 0!important
}
  .comm-search {
    padding-top: 16px;
    flex-wrap: wrap;
    position: fixed;
    background-color: #fff;
    margin-top: -85px;
    transition: 0.2s;
    display: flex;
    align-items: center;
    padding-left: 16px;
    z-index: 50;
    box-shadow: 0 1px 2px rgba(33, 37, 46, 0.12);
    display: flex;
    .ant-row .ant-col{
      width: 100%;
    }
    .ant-row {
      margin-bottom: 16px;
      width: 14.28%;
      margin-right: 0;
      padding-right: 16px;
      .ant-col {
        width: 100%;
      }
    }
    .of-fb-11 {
      flex-basis: 300px;
    }
  }
.ant-modal-body {
 padding: 0!important;
}
.progressBox {
  display: flex;
  align-items: center;
  span{
    min-width:28px;
    display: block;
  }
}
.progressBar {
  position: relative;
  width: 90%;
  height: 12px;
  line-height: 12px;
  font-size: 12px;
  text-align: center;
  border-radius: 6px;
  background: #EAECF0;
  overflow: hidden;
  margin: 0 5px;
  .currentDataBar {
    position: absolute;
        background: linear-gradient(to right, #FAD961, #F76B1C);
    height:100%;
    border-radius:6px;
    top: 0;
    left: 0;
  }
  .dataBar {
    position: absolute;
    top: 0;
    left: 0;
    width: 3px;
    height: 100%;
    background: rgba(0, 0, 0, 0.2);
    cursor: pointer;
    // border-right: 1px solid rgba(0, 0, 0, 0.2);
  }
    .avgData{

    background: rgba(0, 0, 0, 0.18);
    // border-right: 1px solid rgba(0, 0, 0, 0.2);
  }
    .opData{

    background: rgba(0, 0, 0, 0.25);
    // border-right: 1px solid rgba(0, 0, 0, 0.2);
  }
    .serData{

    background: rgba(0, 0, 0, 0.25);
    // border-right: 1px solid rgba(0, 0, 0, 0.2);
  }

}
.service-information-btn-box{
  width: 214px!important
}
}
.legendBox {
  display: flex;
  align-items: flex-start;
  justify-content: center;
  .APU-item,
  .recent-item {
    display: flex;
    align-items: center;
    margin-right: 15px;
    div {
      width: 15px;
      height: 15px;
      border-radius: 50%;
      background: #EE5396;
      margin-right: 5px;
    }
  }

  .recent-item{
    div {
       background: #1192E8;
    }
  }
  .service-limit-item {
    margin-right: 15px;
    img {
      width: 25px;
      height: 25px;
      margin-right: 5px;
    }
  }
}

@media screen and (max-width: 1680px) {
  .service-information-main{
    .ant-row:not(.service-information-btn-box)  {
      width: 14%!important
    }
  }
}
@media screen and (max-width: 1440px) {
  .service-information-main{
    .ant-select{
      min-width: 100%!important;
    }
    .ant-row:not(.service-information-btn-box)  {
        width:12.2%!important
    }
  }
}
  .service-information-main .progressBar{
     .normal-data-bar{
    background: #5a87f7!important;
  }
  }
</style>
